import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert';
import '../model/cart_model.dart';

class CartProvide with ChangeNotifier{
  List<CartInfoModel> cartList=[];
  String cartString = '';
  double allPrice = 0;
  int allGoodsCount = 0; // 商品总数量
  bool isAllSelected = false; // 是不是全选


  save(goodsId,goodsName,count,price,images) async{
    //初始化SharedPreferences
    SharedPreferences prefs = await  SharedPreferences.getInstance();
    cartString = prefs.getString('cartInfo');  //获取持久化存储的值
    //判断cartString是否为空，为空说明是第一次添加，或者被key被清除了。
    //如果有值进行decode操作
    var temp = cartString == null?[]:json.decode(cartString.toString());
    //把获得值转变成List
    List<Map> tempList= (temp as List).cast();
    //声明变量，用于判断购物车中是否已经存在此商品ID
    var isHave= false;        //默认为没有
    int ival=0;               //用于进行循环的索引使用
    allPrice = 0;
    allGoodsCount = 0;        // 商品总数量
    tempList.forEach((item){  //进行循环，找出是否已经存在该商品
      //如果存在，数量进行+1操作
      if(item['goodsId']==goodsId){
        tempList[ival]['count']=item['count']+1;
         //关键代码-----------------start
        cartList[ival].count++;
         //关键代码-----------------end
        isHave=true;
      }
      if(item['isCheck']){
        allPrice +=(item['count']*item['price']);
        allGoodsCount +=  item['count'];
      }
      ival++;
    });
    //  如果没有，进行增加
    if(!isHave){
       //关键代码-----------------start
          Map<String, dynamic> newGoods={
            'goodsId':goodsId,
            'goodsName':goodsName,
            'count':count,
            'price':price,
            'images':images,
            'isCheck':true
          };
          tempList.add(newGoods);
          cartList.add(new CartInfoModel.fromJson(newGoods));
          allPrice +=(count*price);
          allGoodsCount +=  count;
       //关键代码-----------------end
    }
   
    
    //把字符串进行encode操作，
    cartString= json.encode(tempList).toString();
    // print('>>>>>>>$cartString');
    prefs.setString('cartInfo', cartString);//进行持久化
    await getCartInfo();
    notifyListeners();
  }

  remove() async{
    SharedPreferences prefs = await SharedPreferences.getInstance();
    cartList = [];
    print('清空购物车');
    prefs.remove('cartInfo');
  }

  // 将数据model化
  getCartInfo() async{
    SharedPreferences prefs = await SharedPreferences.getInstance();
    cartString = prefs.getString('cartInfo');
    cartList = [];
    isAllSelected = true;
    if(cartString != null){
      List<Map> tempList = (json.decode(cartString.toString())as List).cast();
      // 初始化 
      allPrice = 0;
      allGoodsCount = 0;
      tempList.forEach((item)=>{
          if(item['isCheck']){
            allPrice +=(item['count']*item['price']),
            allGoodsCount +=  item['count']
          }else{
            isAllSelected = false
          },
          cartList.add(CartInfoModel.fromJson(item))
      });
    }
    notifyListeners();
  }

  // 删除单个商品数据
  deleteGoods(String goodsId) async{
      SharedPreferences prefs = await SharedPreferences.getInstance();
      cartString = prefs.getString('cartInfo');
      List<Map> tempList = (json.decode(cartString.toString()) as List ).cast();
      int tempIndex = 0;
      int delIndex = 0;
      tempList.forEach((item)=>{
        if(item['goodsId'] == goodsId ){
          delIndex = tempIndex
        },
        tempIndex++
      });
      print(delIndex);
      print('删除成功');
      tempList.removeAt(delIndex);
       //把字符串进行encode操作，
      cartString= json.encode(tempList).toString();
      prefs.setString('cartInfo', cartString);//进行持久化
      await getCartInfo();
  }

  // 单个商品选中
  changCheckState(CartInfoModel cartItme) async{
      SharedPreferences prefs = await SharedPreferences.getInstance();
      cartString = prefs.getString('cartInfo');
      List<Map> tempList = (json.decode(cartString.toString()) as List ).cast();
      int tempInde = 0;
      int changIndex = 0;
      tempList.forEach((item){
        if(item['goodsId']==cartItme.goodsId){
          changIndex = tempInde;
        }
        tempInde++;
      });
      tempList[changIndex] = cartItme.toJson();
      cartString = json.encode(tempList).toString();
      prefs.setString('cartInfo', cartString);
      await getCartInfo(); 
  }

  // 是不是全部选中
  changAllselectedBtn(bool isCheck) async{
    SharedPreferences prefs = await SharedPreferences.getInstance();
    cartString = prefs.getString('cartInfo');
    List<Map> tempList = (json.decode(cartString.toString()) as List ).cast();
    List<Map> newList = [];
      tempList.forEach((item){
        var newItem = item;
        newItem['isCheck'] = isCheck;
        newList.add(newItem);
      });
      cartString = json.encode(newList).toString();
      prefs.setString('cartInfo', cartString);
      await getCartInfo(); 
    }

  // 商品增加
  addGoodsNum(String goodsId) async{
    SharedPreferences prefs = await SharedPreferences.getInstance();
    cartString = prefs.getString('cartInfo');
    List<Map> tempList = (json.decode(cartString.toString()) as List ).cast();
    int tempIndex = 0;
    int goodsIndex = 0;
    tempList.forEach((item){
      if(item['goodsId'] == goodsId){
        goodsIndex = tempIndex;
      }
      tempIndex++;
    });
    tempList[goodsIndex]['count'] = tempList[goodsIndex]['count']+1;
    cartString = json.encode(tempList).toString();
    prefs.setString('cartInfo', cartString);
    await getCartInfo(); 
  }

  // 商品减少
  reduceGoodsNum(String goodsId) async{
    SharedPreferences prefs = await SharedPreferences.getInstance();
    cartString = prefs.getString('cartInfo');
    List<Map> tempList = (json.decode(cartString.toString()) as List ).cast();
    int tempIndex = 0;
    int goodsIndex = 0;
    tempList.forEach((item){
      if(item['goodsId'] == goodsId){
        goodsIndex = tempIndex;
      }
      tempIndex++;
    });
    tempList[goodsIndex]['count']--;
    if(tempList[goodsIndex]['count']==0){
      deleteGoods(goodsId);
    }else{
      cartString = json.encode(tempList).toString();
      prefs.setString('cartInfo', cartString);
      await getCartInfo(); 
    }
  }
}


